package com.appbee.article.client.presenter;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.appbee.article.shared.ArticleProxy;
import com.appbee.article.shared.ArticleRequestFactory;
import com.appbee.article.shared.ArticleServiceRequest;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;

@Singleton
public class ArticleDataProvider
{
	private final ArticleRequestFactory articleRequestFactory;
	private FetchCommand command;
	private final Scheduler scheduler;

	@Inject
	public ArticleDataProvider(	ArticleRequestFactory requestProvider,
								Scheduler scheduler)
	{
		this.articleRequestFactory = requestProvider;
		this.scheduler = scheduler;

	}

	public ArticleRequestFactory getArticleRequestFactory()
	{
		return articleRequestFactory;
	}

	public void getByStrId(String strId, Receiver<ArticleProxy> receiver)
	{
		if (command == null)
		{
			command = new FetchCommand();
			scheduler.scheduleDeferred(command);
		}
		Request<ArticleProxy> request = command.articleService
				.getByStrId(strId);
		request.to(receiver);
	}

	public class FetchCommand implements ScheduledCommand
	{
		private final ArticleServiceRequest articleService;

		public FetchCommand()
		{
			articleService = articleRequestFactory.getArticleService();
		}

		@Override
		public void execute()
		{
			articleService.fire();
			command = null;
		}

	}

}
